package com.example.allshengmedical.experimentanalyze.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.example.allshengmedical.R;
import com.example.allshengmedical.base.BaseActivity;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.experimentanalyze.presenter.AnalyzeBrowsePresenter;
import com.example.allshengmedical.experimentanalyze.view.IAnalyzeBrowseView;
import com.example.allshengmedical.experimentnew.activity.KeyboardActivity;
import com.example.allshengmedical.experimentnew.bean.FileBean;
import com.example.allshengmedical.experimentnew.bean.FolderBean;
import com.example.allshengmedical.experimentrun.activity.BrowseActivity;
import com.example.allshengmedical.experimentrun.activity.RunPreviewActivity;
import com.example.allshengmedical.experimentrun.activity.BrowseActivity.FileAdapter;
import com.example.allshengmedical.experimentrun.activity.BrowseActivity.FolderAdapter;
import com.example.allshengmedical.experimentrun.presenter.BrowsePresenter;
import com.example.allshengmedical.experimentrun.view.IBrowseView;
import com.example.allshengmedical.mainmenu.activity.MainMenuActivity;
import com.example.allshengmedical.util.ByAlert;
import com.example.allshengmedical.util.FileManagerUtil;
import com.example.allshengmedical.util.LoadingDialog;
import com.example.allshengmedical.util.LogUtil;
import com.example.allshengmedical.util.SharedPreferencesUtils;

//分析的文件浏览器
public class AnalyzeBrowseActivity extends BaseActivity implements
		IAnalyzeBrowseView, OnClickListener {

	public final int TASK_LOOP_COMPLETE = 0;
	ProgressDialog pd;

	private TextView searchTv;
	private ListView folderList, fileList;

	private FileManagerUtil fileManagerUtil;

	private AnalyzeBrowsePresenter browsePresenter;
	private boolean menuboo;
	private PopupWindow menuPopupWindow;

	private FolderAdapter folderAdapter;
	private FileAdapter fileAdapter;

	private FileBean fileBean;

	private Boolean folderSelector = true;

	// 数据
	String folderName;
	String fileName;
	private String appFilePath = Environment.getExternalStorageDirectory()
			+ "/" + "AllShengMedical";

	@Override
	protected int setcontent() {
		return R.layout.activity_run_browse;
	}

	@Override
	protected void initView() {
		SharedPreferencesUtils.put(AnalyzeBrowseActivity.this,
				"positionsArrayList", "");
		fileManagerUtil = new FileManagerUtil();
		browsePresenter = new AnalyzeBrowsePresenter(this);
		browsePresenter.initAppHead();
		browsePresenter.initBottomView();

		initFolderListView();
		initFileListView();

	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	@Override
	public void initAppHead() {
		setActionBar();
		setSystemTime();

	}

	@Override
	public void initBottomView() {
		setBottomView();

	}

	@Override
	public void searchFunction() {
		// 点击查询的时候，清空之前的点击状态，将搜索框清空，显示全部文件。
		folderSelector = false;
		for (int i = 0; i < folderList.getCount() - 1; i++) {
			fileManagerUtil.getFolderNames().get(i).setIsSelected("");
		}
		folderAdapter.upData(fileManagerUtil.getFolderNames());
		folderAdapter.notifyDataSetChanged();
		searchTv.setText("");

		fileAdapter = new FileAdapter(BaseApplication.getContext(), null,
				fileBean);

		fileList.setAdapter(fileAdapter);

		Intent keyBoardIntent = new Intent(AnalyzeBrowseActivity.this,
				KeyboardActivity.class);
		keyBoardIntent.putExtra("folderName", searchTv.getText().toString());
		keyBoardIntent.putExtra("title", "Search");
		startActivityForResult(keyBoardIntent, 104);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.searchTv:
			browsePresenter.searchFunction();
			break;
		}

	}

	// 设置actionBar
	public void setActionBar() {
		Button leftfirstBtn;
		TextView title;

		leftfirstBtn = BindView(R.id.leftfirst_btn);
		title = BindView(R.id.title);

		leftfirstBtn.setVisibility(View.VISIBLE);
		leftfirstBtn.setText(R.string.item_actionbar_home);
		title.setText(R.string.filemanagerActivity_title);

		leftfirstBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				BaseApplication.getInstance().finishAll();
				Intent intent = new Intent(AnalyzeBrowseActivity.this,
						MainMenuActivity.class);
				startActivity(intent);
			}
		});

	}

	// 获取当前时间的方法
	public void setSystemTime() {

		TextView date, fileName;
		date = BindView(R.id.date);
		fileName = BindView(R.id.file_name);

		// 获取系统时间
		SimpleDateFormat sdfDate = new SimpleDateFormat("MM dd,yyyy");
		date.setText(sdfDate.format(new Date()));

		// 文件路径置空
		fileName.setText("");

	}

	// 设置bottom布局
	public void setBottomView() {
		Button bottomLeftFistBtn, bottomCenterBtn;
		final Button bottomRightBtn;

		bottomLeftFistBtn = BindView(R.id.bottomLeftFistBtn);
		bottomCenterBtn = BindView(R.id.bottomCenterBtn);
		bottomRightBtn = BindView(R.id.bottomRightBtn);

		bottomLeftFistBtn.setVisibility(View.VISIBLE);
		// bottomCenterBtn.setVisibility(View.VISIBLE);
		bottomRightBtn.setVisibility(View.VISIBLE);

		bottomLeftFistBtn.setText(R.string.bottomView_back);
		// TODO 这个button的文字不确定暂时用A代替
		bottomCenterBtn.setText("A"); // 不确定！！！！！！！
		bottomRightBtn.setText(R.string.bottomView_next);

		bottomLeftFistBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				System.gc();
				pd = ProgressDialog.show(AnalyzeBrowseActivity.this, "",
						"loading...", true, true);

				new Thread() {
					public void run() {
						try {
							Intent intent = new Intent(
									AnalyzeBrowseActivity.this,
									MainMenuActivity.class);
							// intent.putStringArrayListExtra("data_list1",
							// data_list1);s
							startActivity(intent);
						} finally {
							messageListener
									.sendEmptyMessage(TASK_LOOP_COMPLETE);
						}
					}
				}.start();

			}
		});

		bottomCenterBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// ByAlert.alert("A");

			}
		});
		bottomRightBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				final StringBuilder contextString = new StringBuilder();
				Boolean bool = false;
				// 需要判断不能为空两个选中都不能为空。
				for (FolderBean folderBean : fileManagerUtil.getFolderNames()) {
					if ("1".equals(folderBean.getIsSelected())) {
						SharedPreferencesUtils.put(AnalyzeBrowseActivity.this,
								BaseApplication.FILEMANGER_PREPAREFOLDERPATH,
								folderBean.getFolderName() + "");

						bool = false;
						break;

					} else {
						bool = true;
					}
				}
				if (!bool) {
					for (FileBean fileBean : fileManagerUtil.getFileNames()) {
						if ("1".equals(fileBean.getIsSelected())) {
							SharedPreferencesUtils.put(
									AnalyzeBrowseActivity.this,
									BaseApplication.FILEMANGER_PREPAREFILENAME,
									fileBean.getFileName() + "");
							bool = false;
							break;
						} else {
							bool = true;
						}
					}
				}

				if (bool) {
					ByAlert.alert(getString(R.string.ana_brow_checkfile));
					return;
				}
				folderName = SharedPreferencesUtils.get(
						AnalyzeBrowseActivity.this,
						BaseApplication.FILEMANGER_PREPAREFOLDERPATH, "")
						+ "";
				fileName = SharedPreferencesUtils.get(
						AnalyzeBrowseActivity.this,
						BaseApplication.FILEMANGER_PREPAREFILENAME, "")
						+ "";
				if(fileName.contains("!")){
					ByAlert.alert(getString(R.string._lessDataError));
					return;
				}

				String path = appFilePath + "/" + folderName;

				File file = new File(path + "/" + fileName);
				BufferedReader reader = null;
				try {
					System.out.println("以行为单位读取文件内容，一次读一整行：");
					reader = new BufferedReader(new FileReader(file));
					String tempString = null;
					int line = 1;
					// 一次读入一行，直到读入null为文件结束
					while ((tempString = reader.readLine()) != null) {
						// 显示行号
						// System.out.println("line " + line + ": "
						// +
						// tempString);
						// Log.e("--", tempString);
						contextString.append(tempString);
						contextString.append(",");
						line++;
					}
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (reader != null) {
						try {
							reader.close();

						} catch (IOException e1) {
						}
					}
				}
				if (!contextString.toString().contains("Aisle")) {
					ByAlert.alert(getString(R.string.ana_brow_layout1_));
					return;
				}
				if (!contextString.toString().contains("dataSourceListBlock1")
						| !contextString.toString().contains(
								"dataSourceListBlock2")) {
					ByAlert.alert(getString(R.string.ana_brow_genepan));
					return;
				}
				if (!contextString.toString().contains("Methods")) {
					ByAlert.alert(getString(R.string.ana_brow_methods_));
					return;
				}
				if (!contextString.toString().contains(",,Channel1")) {
					// 在运行试验的时候应该将判断条件前面加
					ByAlert.alert(getString(R.string.ana_brow_havadata));
					return;
				}

				pd = ProgressDialog.show(AnalyzeBrowseActivity.this, "",
						"loading...", true, false);

				new Thread() {

					public void run() {
						try {

							Intent intent = new Intent(
									AnalyzeBrowseActivity.this,
									AnalyzeAmplificationplotActivity.class);
							startActivity(intent);

						} finally {
							messageListener
									.sendEmptyMessage(TASK_LOOP_COMPLETE);
						}
					}
				}.start();

			}
		});
	}

	// 文件夹的ListView适配器
	public class FolderAdapter extends BaseAdapter {
		private Context mContext;
		ArrayList<FolderBean> folderNames;

		private LayoutInflater inflater;
		boolean defaultShow = false;

		public FolderAdapter() {
			super();
		}

		public FolderAdapter(Context mContext, ArrayList<FolderBean> folderNames) {
			super();
			this.folderNames = folderNames;
			this.mContext = mContext;

			inflater = LayoutInflater.from(mContext);
		}

		public void upData(ArrayList<FolderBean> folderNames) {

			this.folderNames = folderNames;

		}

		class ViewHolder {

			TextView folderNameTv;
			LinearLayout line;

		}

		@Override
		public int getCount() {
			return folderNames != null ? folderNames.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return folderNames != null ? folderNames.get(position) : null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;

			if (holder == null) {
				convertView = inflater.inflate(R.layout.item_listview_folder,
						null);
				holder = new ViewHolder();

				holder.folderNameTv = (TextView) convertView
						.findViewById(R.id.folderNameTv);

				holder.line = (LinearLayout) convertView
						.findViewById(R.id.line);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.folderNameTv.setText(folderNames.get(position)
					.getFolderName());
			if ("1".equals(folderNames.get(position).getIsSelected())) {
				holder.line.setBackgroundColor(getResources().getColor(
						R.color.selected_color));
			} else {
				holder.line.setBackgroundColor(getResources().getColor(
						R.color.white));
			}

			// holder.folderNameTv.setText(folderNames.get(position)
			// .getFolderName());

			// if (position == 0) {
			// for (FolderBean bean : folderNames) {
			// if ("Default".equals(bean.getFolderName())) {
			// holder.folderNameTv.setText("Default");
			//
			// if ("1".equals(bean.getIsSelected())) {
			// holder.line.setBackgroundColor(getResources()
			// .getColor(R.color.selected_color));
			// } else {
			// holder.line.setBackgroundColor(getResources()
			// .getColor(R.color.white));
			// }
			// }
			// }
			// } else {
			// // for (FolderBean bean : folderNames) {
			// if ("Default".equals(folderNames.get(position).getFolderName()))
			// {
			// defaultShow = true;
			// holder.folderNameTv.setText(folderNames.get(position - 1)
			// .getFolderName());
			// if ("1".equals(folderNames.get(position - 1)
			// .getIsSelected())) {
			// holder.line.setBackgroundColor(getResources().getColor(
			// R.color.selected_color));
			// } else {
			// holder.line.setBackgroundColor(getResources().getColor(
			// R.color.white));
			// }
			// return convertView;
			// }
			// // else {
			//
			// if (defaultShow) {
			// holder.folderNameTv.setText(folderNames.get(position)
			// .getFolderName());
			// if ("1".equals(folderNames.get(position).getIsSelected())) {
			// holder.line.setBackgroundColor(getResources().getColor(
			// R.color.selected_color));
			// } else {
			// holder.line.setBackgroundColor(getResources().getColor(
			// R.color.white));
			// }
			//
			// } else {
			// holder.folderNameTv.setText(folderNames.get(position - 1)
			// .getFolderName());
			// if ("1".equals(folderNames.get(position - 1)
			// .getIsSelected())) {
			// holder.line.setBackgroundColor(getResources().getColor(
			// R.color.selected_color));
			// } else {
			// holder.line.setBackgroundColor(getResources().getColor(
			// R.color.white));
			// }
			// }
			//
			// }
			// }
			// }

			return convertView;
		}

	}

	// 文件的ListView适配器
	public class FileAdapter extends BaseAdapter {
		private Context mContext;
		private ArrayList<FileBean> fileNames;
		private LayoutInflater inflater;
		private FileBean fileBean;

		public FileAdapter() {
			super();
		}

		public FileAdapter(Context mContext, ArrayList<FileBean> fileNames,
				FileBean fileBean) {
			super();
			this.fileNames = fileNames;
			this.mContext = mContext;
			this.fileBean = fileBean;
			inflater = LayoutInflater.from(mContext);
		}

		public void clear() {
			this.fileBean = new FileBean();
			ArrayList<FileBean> collection = new ArrayList<FileBean>();
			this.fileNames = collection;
			notifyDataSetChanged();
		}

		class ViewHolder {

			TextView fileNameTv, createTimeTv;
			LinearLayout line;

		}

		@Override
		public int getCount() {
			return fileNames != null ? fileNames.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return fileNames.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (holder == null) {
				convertView = inflater.inflate(R.layout.item_listview_file,
						null);
				holder = new ViewHolder();

				holder.fileNameTv = (TextView) convertView
						.findViewById(R.id.fileNameTv);
				holder.createTimeTv = (TextView) convertView
						.findViewById(R.id.createTimeTv);
				holder.line = (LinearLayout) convertView
						.findViewById(R.id.line);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			// if (position == 0) {
			// if (TextUtils.isEmpty(fileBean.getFileName())) {
			// StringBuffer fileName = new StringBuffer();
			// fileName.append("FileName");
			// SimpleDateFormat myFmt = new SimpleDateFormat(
			// "yyyy-MM-dd-HH-mm-ss");
			// fileName.append(myFmt.format(System.currentTimeMillis()));
			// fileBean.setFileName(fileName + "");
			// }
			//
			// holder.fileNameTv.setText(fileBean.getFileName() + "");
			// SimpleDateFormat myFmt2 = new SimpleDateFormat(
			// "yyyy-MM-dd HH:mm:ss");
			// holder.createTimeTv.setText(myFmt2.format(System
			// .currentTimeMillis()));
			// holder.line.setBackground(getResources().getDrawable(
			// R.color.selected_color));
			// } else {
			// holder.fileNameTv.setText(fileNames.get(position - 1)
			// .getFileName());
			// holder.createTimeTv.setText(fileNames.get(position - 1)
			// .getCreateTime());
			// }

			holder.fileNameTv.setText(fileNames.get(position).getFileName()
					+ "");

			holder.createTimeTv.setText(fileNames.get(position).getCreateTime()
					+ "");
			if (TextUtils.isEmpty(fileNames.get(position).getIsSelected())) {
				holder.line.setBackground(getResources().getDrawable(
						R.color.white));
			} else {
				holder.line.setBackground(getResources().getDrawable(
						R.color.selected_color));
			}

			return convertView;
		}
	}

	// 配置文件夹的listView
	private void initFolderListView() {
		fileManagerUtil.getFolderInfo();
		// for (FolderBean bean : fileManagerUtil.getFolderNames()) {
		// if ("Default".equals(bean.getFolderName())) {
		// bean.setIsSelected("1");
		// }
		// }

		fileManagerUtil.getFolderNames();

		ArrayList<FolderBean> folderNamesCopy = new ArrayList<FolderBean>();
		folderNamesCopy.addAll(fileManagerUtil.getFolderNames());
		int index = 0;
		for (int i = 0; i < fileManagerUtil.getFolderNames().size(); i++) {
			if ("Default".equals(fileManagerUtil.getFolderNames().get(i)
					.getFolderName())) {
				index = i;
			}
		}
		fileManagerUtil.getFolderNames().clear();
		try {
			fileManagerUtil.getFolderNames().add(folderNamesCopy.get(index));
			folderNamesCopy.remove(index);
		} catch (Exception e) {
			// TODO
		}

		fileManagerUtil.getFolderNames().addAll(folderNamesCopy);

		folderAdapter = new FolderAdapter(this,
				fileManagerUtil.getFolderNames());

		folderList.setAdapter(folderAdapter);

		folderList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// folderList.getCount();
				for (int i = 0; i < folderList.getCount(); i++) {

					if ("".equals(searchTv.getText())) {
						fileManagerUtil.getFolderNames().get(i)
								.setIsSelected("");
					} else {
						fileManagerUtil.getSearchFolderNames().get(i)
								.setIsSelected("");
					}

				}

				// 判断是否在搜索
				if ("".equals(searchTv.getText())) {

					fileManagerUtil.getFolderNames().get(position)
							.setIsSelected("1");
					folderAdapter.upData(fileManagerUtil.getFolderNames());
					folderAdapter.notifyDataSetChanged();
				} else {
					fileManagerUtil.getSearchFolderNames().get(position)
							.setIsSelected("1");
					folderAdapter.upData(fileManagerUtil.getSearchFolderNames());
					folderAdapter.notifyDataSetChanged();
				}

				// // 查询文件夹下面有什么文件！
				fileAdapter.clear();

				getFileInfo(fileManagerUtil.getFolderNames().get(position)
						.getFolderName());
				fileAdapter = new FileAdapter(BaseApplication.getContext(),
						fileManagerUtil.getFileNames(), fileBean);
				// fileAdapter.notifyDataSetChanged();
				// LayoutInflater infla = LayoutInflater.from(BaseApplication
				// .getContext());
				// View footView = infla.inflate(
				// R.layout.item_listview_folder_footview, null);

				fileList.setAdapter(fileAdapter);

				fileList.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {

						for (int i = 0; i < fileManagerUtil.getFileNames()
								.size(); i++) {
							fileManagerUtil.getFileNames().get(i)
									.setIsSelected("");
						}

						fileManagerUtil.getFileNames().get(position)
								.setIsSelected("1");
						fileAdapter.notifyDataSetChanged();
					}
				});

				folderSelector = true;

			}

		});
	}

	private void initFileListView() {
		fileBean = new FileBean("", "Date Time");
		fileAdapter = new FileAdapter(BaseApplication.getContext(),
				fileManagerUtil.getFileNames(), fileBean);
		fileList.setAdapter(fileAdapter);

	}

	// 获取具体文件信息
	private void getFileInfo(String fileName) {
		fileManagerUtil.getFileNames().clear();
		String chosenFilePath = Environment.getExternalStorageDirectory() + "/"
				+ "AllShengMedical/" + "/" + fileName;
		LogUtil.e(chosenFilePath);
		File chosenFile = new File(chosenFilePath);
		File[] chosenFiles = chosenFile.listFiles();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (int i = 0; i < chosenFiles.length - 1; i++) {
			for (int j = i + 1; j < chosenFiles.length; j++) {
				if (chosenFiles[i].lastModified() < chosenFiles[j]
						.lastModified()) {
					File temp = chosenFiles[i];
					chosenFiles[i] = chosenFiles[j];
					chosenFiles[j] = temp;
				}
			}
		}
		for (int i = 0; i < chosenFiles.length; i++) {
			FileBean fileBean = new FileBean();
			fileBean.setFileName(chosenFiles[i].getName());
			// LogUtil.e(chosenFiles[i].getName());
			fileBean.setCreateTime(format.format(chosenFiles[i].lastModified()));
			fileManagerUtil.getFileNames().add(fileBean);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 点击搜索文件夹，返回传值成功
		if (requestCode == 104 && resultCode == 201) {

			String result = data.getExtras().getString("result");
			searchTv.setText(result);
			fileManagerUtil.searchAndSort(result);
			folderAdapter.upData(fileManagerUtil.getSearchFolderNames());
			folderAdapter.notifyDataSetChanged();
		}
		// 点击搜索文件夹，返回传值失败
		if (requestCode == 104 && resultCode == 202) {
			fileManagerUtil.getFolderInfo();
		}

	}

	private Handler messageListener = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.arg1) {
			case TASK_LOOP_COMPLETE:
				pd.dismiss();
				break;

			}
		}
	};

	// protected void onDestroy() {
	// if (reader != null) {
	// try {
	// reader.close();
	//
	// } catch (IOException e1) {
	// }
	// }
	// };
}
